package com.aegis.manage.manager;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
@Component
public class AeNacosConfigManager {

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String nacosServerAddr;

    @Value("${spring.cloud.nacos.username}")
    private String username;

    @Value("${spring.cloud.nacos.password}")
    private String password;

    @Value("${spring.cloud.nacos.config.namespace}")
    private String namespace;

    private static final String GROUP = "DEFAULT_GROUP";

    private final RestTemplate restTemplate = new RestTemplate();

    public boolean publishYamlConfig(String dataId, String content) {
        return publishConfig(dataId, GROUP, content, "yaml");
    }

    public String getNacosConfig(String dataId) {
        String url = "http://" + nacosServerAddr + "/nacos/v1/cs/configs"
                + "?dataId=" + dataId
                + "&group=" + GROUP
                + "&tenant=" + namespace
                + "&username=" + username
                + "&password=" + password;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        return response.getBody();
    }


    public boolean publishConfig(String dataId, String group, String content, String type) {
        String url = "http://" + nacosServerAddr + "/nacos/v1/cs/configs";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        Map<String, String> params = new LinkedHashMap<>();
        params.put("dataId", dataId);
        params.put("group", group);
        params.put("content", content);
        params.put("type", type);
        params.put("tenant", namespace);
        params.put("username", username);
        params.put("password", password);

        StringBuilder body = new StringBuilder();
        params.forEach((k, v) -> body.append(k).append("=").append(v).append("&"));
        String requestBody = body.substring(0, body.length() - 1);

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return "true".equalsIgnoreCase(response.getBody());
    }
}
